package com.kakaxi.mybilibili.module.home.find.presenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kakaxi.mybilibili.bean.FindCenterItemBean;
import com.kakaxi.mybilibili.common.WebParamConst;
import com.kakaxi.mybilibili.module.home.find.model.FindCenterModel;
import com.kakaxi.mybilibili.module.home.find.model.IFindCenterModel;
import com.kakaxi.mybilibili.module.home.find.view.IFindCenterView;
import com.vincestyling.netroid.Listener;
import com.vincestyling.netroid.NetroidError;

import java.util.List;

/**
 * 发现活动控制层实现类
 * Created by kakaxi on 16/11/26.
 */

public class FindCenterPresenter implements IFindCenterPresenter {

    private IFindCenterModel mModel;

    private IFindCenterView mView;

    public FindCenterPresenter(IFindCenterView findCenterView) {
        mView = findCenterView;
        mModel = new FindCenterModel();
    }

    @Override
    public void initCenterData(int type) {
        mView.showLoading();
        getCenterListData(type);
    }

    @Override
    public void refreshCenterData(int type) {
        getCenterListData(type);
    }

    /**
     * 获取数据
     *
     * @param type 类型
     */
    private void getCenterListData(int type) {
        mModel.getCenterListData(type, new Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                super.onSuccess(response);
                mView.hideLoading();
                if (response.getString(WebParamConst.RESPONSE_CODE).equals(WebParamConst
                        .RESULT_CODE_OK)) {
                    JSONArray centerJsonArr = response.getJSONArray(WebParamConst
                            .RESPONSE_DATA_FIND_CENTER_LIST);
                    List<FindCenterItemBean> findCenterItemBeenList = JSON.parseArray
                            (centerJsonArr.toString(), FindCenterItemBean.class);
                    // 移除没有封面的
                    for (int i = 0; i < findCenterItemBeenList.size(); i++) {
                        FindCenterItemBean itemBean = findCenterItemBeenList.get(i);
                        if (itemBean.getCover() == null || itemBean.getCover().equals("")) {
                            findCenterItemBeenList.remove(i);
                            i--;
                        }
                    }
                    mView.showCenterData(findCenterItemBeenList);
                } else {
                    mView.showMessage(response.getString(WebParamConst.RESPONSE_MESSAGE));
                }
            }

            @Override
            public void onError(NetroidError error) {
                super.onError(error);
                mView.hideLoading();
                mView.showMessage(error.getMessage());
            }
        });
    }

}
